#!/usr/bin/python3
from itertools import count
import time
import pymongo
import sys
import os
from print_html2pdf import main as printmain
import threading

myclient = pymongo.MongoClient(
    "mongodb://admin:admin@192.168.3.21:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000")
mydb = myclient["mp_weixin"]


def main(mp_name, msg_cnt=100, skip=0, years=1):
    now = time.time()
    over_time = int (now-365*24*60*60*int(years))
    for msg in mydb['gzh_wz'].find({"name": mp_name}, {"name": 1, "link": 1, "title": 1, "update_time": 1, "create_time": 1}).skip(int(skip)).batch_size(5):
        if msg["update_time"] < over_time | msg["create_time"] < over_time:
            print("公众号《%s》%s年的文章保存pdf成功，一共%d条记录"%(mp_name,years,))
            break
        print("正在转换文章:"+msg['title'], msg["link"])
        threading.Thread(target=printmain, args=(
            "./gzh_pdf/%s" % (mp_name), msg['link'])).start()
        # py.exe C:\Users\GUOKA\Desktop\app\wechat-history\print_html2pdf.py './gzh_pdf/淘淘升学' 'http://mp.weixin.qq.com/s?__biz=MzI2Mzc0MjI0MQ==&mid=2247502111&idx=1&sn=be43177cd8dc5ef35ccf29425e1573d3&chksm=eab5bf51ddc236475ce6e3aebbc0f280ab972eb267b8866a7eec91f4dc83ea2b2d9ff5525255#rd'
        # print_html2pdf.main("./gzh_pdf/%s"%(mp_name),msg['link'])
        time.sleep(30)


if __name__ == '__main__':
    mp_name = sys.argv[1]
    msg_cnt = sys.argv[2]
    skip = sys.argv[3]
    years = sys.argv[4]
    main(mp_name, msg_cnt, skip, years)
